package com.practice.designMode.coupon;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.util.Date;

/**
 * 规则校验引擎类
 */
public class RuleEngine {

    private CouponStrategyFactory factory;

    public RuleEngine() {
        this.factory = new CouponStrategyFactory();
    }

    public RuleEngine(CouponStrategyFactory factory) {
        this.factory = factory;
    }

    public boolean verifyCoupon(Order order,UserCoupon coupon) {
        // 解析规则JSON
        JSONObject ruleJson = JSON.parseObject(coupon.getRuleJson());

        if(!validateCommonRule(order,coupon,ruleJson)){
            return false;
        }

        CouponRuleStrategy strategy = factory.getStrategy(CouponType.typeOf(coupon.getType()));
        if (strategy == null) {
            return false;
        }
        return strategy.validate(order, coupon, ruleJson);
    }

    private boolean validateCommonRule(Order order, UserCoupon coupon, JSONObject ruleJson) {
        Date currentTime = new Date();
        if (currentTime.after(coupon.getExpireTime())) {
            return false;
        }

        // 校验适用门店
        if (ruleJson.containsKey("applicableStores")) {
            String[] stores = ruleJson.getString("applicableStores").split(",");
            boolean validStore = false;
            for (String store : stores) {
                if (store.equals(String.valueOf(order.getStoreId()))) {
                    validStore = true;
                    break;
                }
            }
            if (!validStore) {
                return false;
            }
        }

        // 其它通用规则
        // ...
        return true;
    }
}
